<?php

namespace app\models;

use Yii;

/**
 * 扩展model
 * 单表更新，删除，多表关联查询的利器
 * @author administrator
 */
class BaseModel extends \yii\db\ActiveRecord
{
    //默认主键id,如果主键id不同,请在自己的模型类重定义该属性
   protected $_primaryKey = 'id';

    /**
     * 扩展基础service 列表操作
     * @param string $fields 查询的表字段
     * @param array $param 所有的查询操作条件数组
     * @return array
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbList($fields = '*', $param = [])
    {
        $page   = (isset($param['page']) && $param['page'] > 0) ? $param['page'] : 1;
        $limit  = (isset($param['limit']) && $param['limit'] > 0) ? $param['limit'] : 15;
        $offset = ($page - 1) * $limit;
        $group  = isset($param['group']) ? $param['group'] : null;
        $order  = isset($param['order']) ? $param['order'] : "{$this->tableName()}.{$this->_primaryKey} DESC";
        $where  = isset($param['where']) ? $param['where'] : [];
        $bind   = isset($param['bind']) ? $param['bind'] : [];
        $query  = Yii::$container->get('yii\db\Query')
            ->select($fields)
            ->from($this->tableName());

        //处理表关联
        if (isset($param['join']) && !empty($param['join'])) {
            foreach ($param['join'] as $k => $v) {
                if ('LEFT' == $v[0]) {
                    $query->leftJoin($v[1], $v[2]);
                } elseif ('RIGHT' == $v[0]) {
                    $query->rightJoin($v[1], $v[2]);
                } else {
                    $query->leftJoin($v[1], $v[2]);
                }
            }
        }
        //如果设置了需要分页 处理分页
        if (isset($param['page']) && $param['page']) {
            $query->limit($limit);
            $query->offset($offset);
        }
        //处理分组
        $group && $query->groupBy($group);
        //处理排序
        $order && $query->orderBy($order);
        $where && $query->filterWhere($where);
        $bind && $query->params($bind);
        $return['count'] = $query->count('*', $this->getDb());
        $return['list']  = $query->all($this->getDb());
        return $return;
    }

    /**
     * 扩展基础service 获得一条记录
     * @param string $fields
     * @param string $id
     * @param array $param
     * @return mixed
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbGet($fields = '*', $id = 0, $param = [])
    {
        $where = isset($param['where']) ? $param['where'] : [];
        $bind  = isset($param['bind']) ? $param['bind'] : [];
        $order = isset($param['order']) ? $param['order'] : "{$this->tableName()}.{$this->_primaryKey} DESC";
        //如果没有id并且没有where条件  直接返回false
        if (!$id && !$where) {
            return false;
        }
        $query = Yii::$container->get('yii\db\Query')
            ->select($fields)
            ->from($this->tableName());
        //处理表关联
        if (isset($param['join']) && !empty($param['join'])) {
            foreach ($param['join'] as $k => $v) {
                if ('LEFT' == $v[0]) {
                    $query->leftJoin($v[1], $v[2]);
                } elseif ('RIGHT' == $v[0]) {
                    $query->rightJoin($v[1], $v[2]);
                } else {
                    $query->leftJoin($v[1], $v[2]);
                }
            }
        }
        $where && $query->where($where);
        //处理id
        if ($id > 0) {
            $query->andWhere(['and', "{$this->_primaryKey}=:id"]);
            $bind[':id'] = $id;
        }
        $order && $query->orderBy($order);
        $bind && $query->params($bind);
        
        $return = $query->one($this->getDb());

        return $return;
    }

    /**
     * 扩展基础service 单表操作插入操作
     * @param array $data
     * @return int  返回插入的id
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbAdd($data)
    {
        if (empty($data)) {
            return false;
        }
        Yii::$app->db->createCommand()->insert($this->tableName(), $data)->execute();
        return Yii::$app->db->getLastInsertID();
    }

    /**
     * 扩展基础service 单表操作插入多条数据操作
     * @param array $data
     * @return int  返回插入的id
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbBatchAdd($columns, $rows)
    {
        if (empty($columns) || empty($rows)) {
            return false;
        }
        Yii::$app->db->createCommand()->batchInsert($this->tableName(), $columns, $rows)->execute();
        return Yii::$app->db->getLastInsertID();
    }

    /**
     * 扩展基础service 单表操作删除
     * @param  mixed $ids 数组或者字符串逗号隔开 1,2,3 [1,2,3]
     * @param  array $param 查询条件
     * @return bool true | false
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbDel($ids = '', $param = [])
    {
        $where = isset($param['where']) ? $param['where'] : [];
        $bind  = isset($param['bind']) ? $param['bind'] : [];
        $limit = isset($param['limit']) ? $param['limit'] : null;
        $order = isset($param['order']) ? $param['order'] : null;
        if (!$ids && !$where) {
            return false;
        }
        $condition = '1 ';
        $command   = Yii::$app->db->createCommand();
        //传入的$ids是字符串连接 1,2,3,
        if ($ids && !is_array($ids)) {
            strval($ids);
            $ids = explode(',', $ids);
        }
        if (is_array($ids) && count($ids)) {
            $strIds = implode(',', $ids);
            $condition .= " AND {$this->_primaryKey} in ({$strIds})";
        }
        if ($where) {
            $condition .= " AND {$where}";
        }
        if ($order) {
            $condition .= " order by {$order}";
        }
        if ($limit) {
            $condition .= "limit {$limit}";
        }
        $res = $command->delete($this->tableName(), $condition, $bind)->execute();
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 扩展基础service 单表操作更新
     * @param  array $data 要更新的数据字段
     * @param  mixed $ids 数组或者字符串逗号隔开 1,2,3 [1,2,3]
     * @param  array $param 查询条件
     * @return bool true | false
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbUpdate($ids = '', $data, $param = [])
    {
        $where = isset($param['where']) ? $param['where'] : [];
        $bind  = isset($param['bind']) ? $param['bind'] : [];
        $limit = isset($param['limit']) ? $param['limit'] : null;
        $order = isset($param['order']) ? $param['order'] : null;
        if (!$ids && !$where) {
            return false;
        }
        $condition = '1 ';
        $command   = Yii::$app->db->createCommand();
        //传入的$ids是字符串连接 1,2,3,
        if ($ids && !is_array($ids)) {
            strval($ids);
            $ids = explode(',', $ids);
        }
        if (is_array($ids) && count($ids)) {
            $strIds = implode(',', $ids);
            $condition .= " AND {$this->_primaryKey} in ({$strIds})";
        }
        if ($where) {
            $condition .= " AND {$where}";
        }
        if ($order) {
            $condition .= " order by {$order}";
        }
        if ($limit) {
            $condition .= "limit {$limit}";
        }
        return $command->update($this->tableName(), $data, $condition, $bind)->execute();
    }

    /**
     * 扩展基础service 获得总条数
     * @param array $param 所有的查询操作条件数组
     * @return array
     * @author adminstarator
     * @since 2017-07-10
     */
    public function dbCount($param = [])
    {
        $group = isset($param['group']) ? $param['group'] : null;
        $order = isset($param['order']) ? $param['order'] : "{$this->tableName()}.{$this->_primaryKey} DESC";
        $where = isset($param['where']) ? $param['where'] : [];
        $bind  = isset($param['bind']) ? $param['bind'] : [];
        
        $query = Yii::$container->get('yii\db\Query')
            ->select($this->tableName() .'.' .$this->_primaryKey)
            ->from($this->tableName());
        //处理表关联
        if (isset($param['join']) && !empty($param['join'])) {
            foreach ($param['join'] as $k => $v) {
                if ('LEFT' == $v[0]) {
                    $query->leftJoin($v[1], $v[2]);
                } elseif ('RIGHT' == $v[0]) {
                    $query->rightJoin($v[1], $v[2]);
                } else {
                    $query->leftJoin($v[1], $v[2]);
                }
            }
        }

        //处理分组
        $group && $query->groupBy($group);
        //处理排序
        $order && $query->orderBy($order);
        $where && $query->filterWhere($where);
        $bind && $query->params($bind);
        $count = $query->count();
        return (int) $count;
    }
}
